"""
工具函数
"""
import os
import re
from io import BytesIO
from functools import wraps

import chardet

from src.models.user import User
from src.ui.login import LoginDialog
from src.api.user import get_user_info as api_get_user_info
from src.config import settings


def require_login(func):
    """登陆校验，未登录则自动唤起登录页"""

    @wraps(func)
    def wrapper(*args, **kw):
        if User.get_user(require_login=True):  # 用户已登录
            return func(*args, **kw)
        else:
            with LoginDialog(None) as dlg:
                dlg.ShowModal()
            user = User.get_user(require_login=True)
            if user:
                return func(*args, **kw)
            else:
                return None

    return wrapper


def user_info():
    status, data = api_get_user_info()
    if status == 1000:
        username = User.get_user().username
        amount = data["amount"]
        username = f"用户:{username}  "
        account = f"账户余额:￥{amount}  "
    else:
        username, account = "", ""
    return username, account


def get_allowed_files(
    dirname, suffix=[".pdf", ".PDF", ".png", ".jpg", ".jpeg", ".bmp"]
):
    if not os.path.isdir(dirname):
        return []
    allowed_files = []
    for root, _, files in os.walk(dirname):
        for file_ in files:
            path = os.path.join(root, file_)
            if file_.endswith(tuple(suffix)):
                allowed_files.append(path)
    return allowed_files


def compress_img(path, target_size=1000):
    """压缩图片大小"""
    from PIL import Image

    if not os.path.isfile(path) or not path.lower().endswith(
        (".jpeg", ".jpg", ".png", ".bmp")
    ):
        return
    img = Image.open(path)
    w, h = img.size
    ratio = w / 1000 if w > 1000 else 1
    img = img.resize((1000, int(h / ratio)), Image.ANTIALIAS)

    img_bytes = BytesIO()
    img_format = "jpeg" if path.endswith((".jpg", ".jpeg")) else path.split(".")[-1]
    img.save(img_bytes, format=img_format, quality=85, optimize=True)
    size = len(img_bytes.getvalue()) / 1000  # KB
    while size > target_size:
        img = Image.open(img_bytes)
        img_bytes = BytesIO()
        img.save(img_bytes, format=img_format, quality=85, optimize=True)
        size = len(img_bytes.getvalue())
    return img_bytes.getvalue()


def compare_app_version(verion):
    """对比app版本是否更新"""
    main_v, sec_v, thr_v, date = re.split(r"\.|-", verion)[1:-1]
    _main_v, _sec_v, _thr_v, _date = re.split(r"\.|-", settings.app_version)[1:]

    return f"{date}.{main_v}.{sec_v}.{thr_v}" > f"{_date}.{_main_v}.{_sec_v}.{_thr_v}"


def get_encoding(file_path: str) -> str:
    with open(file_path, "rb") as fin:
        encoding = chardet.detect(fin.read(1000))["encoding"]
        return encoding.replace('GB2312', 'GBK')
